#!/usr/bin/env python3
# -*- coding: utf-8 -*-

try:
	from urllib.request   import urlopen
	from urllib.error     import *
	from bs4			  import BeautifulSoup
except ImportError:
	from urllib2          import *
	from BeautifulSoup    import BeautifulSoup


from assis_const      import *
from assis_ui         import *
from assis_gui        import *

import shelve
import sys



class Connection :
	
	
	def __init__(self, server = DICT_ON_SERVER):
		
		self.server               = server
		self.SEARCH_OPT_SOUGHT    = SEARCH_OPT_SOUGHT
		self.SEARCH_OPT_LANGUAGES = SEARCH_OPT_LANGUAGES
		self.SEARCH_OPT_MODE      = SEARCH_OPT_MODE_PRE

	def consult(self, word):
		
		try:
			response = urlopen(self.server + \
			                   self.SEARCH_OPT_SOUGHT + word + \
						       self.SEARCH_OPT_LANGUAGES + \
						       self.SEARCH_OPT_MODE)
		except URLError as e:
			print(e.reason)
			
		rawdata = response.read().decode("utf-8")
		response.close()
		
		return rawdata
		
		
		
class Session (Connection) : 


	def __init__(self, word = "", local_dict = DICT_ON_LOCAL_HOST):
		
		Connection.__init__(self)
		self.lastSought = word
		self.history = shelve.open(local_dict, 'c')
		
		
	def get_last_dict(self): 
		
		return self.history.get(self.lastSought).dct
		
	def translate(self, word):
		
		self.lastSought = word
		
		
		if self.lastSought in self.history.keys():
			# If so, furnish the correspondent dict encapsulated by the Extract object
			return self.history.get(self.lastSought).dct
			
		self.html = self.consult(self.lastSought)
		extract = Extract(self.html)
		self.history[self.lastSought] = extract
		self.history.sync()
		
	def __del__(self):
		self.history.close()
		

		
class Extract :
	
	
	def __init__(self, html):
		
		self.html      = html
		self.soup      = BeautifulSoup(self.html)
		self.dct       = self.square_en2hu()
				
	def square_en2hu(self):
		
		dct = {}
		en  = []
		hu  = []
		
		for tag in self.soup.find_all( ["span", "a"], {"class" : "prop prop_content freetext"} ):
			if tag.name in ["span"]: 
				if hu: 
					dct[tuple(en)] = tuple(hu)
					en[:] = []
					hu[:] = []
				en.append(tag.text)	
				continue
			else:
				hu.append(tag.text)
				dct.update({tuple(en) : tuple(hu)})

		return dct



if __name__ == "__main__":
	#Default recursion limit has to be altered due to a
	#RuntimeError when BeautifulSoup object being serialized
	sys.setrecursionlimit(10000)
	
	
	ion = Session()
	for word in [ "squalor", "heresy", "Default", "limit", "had", "to", "be", "altered", "due", "to", "Runtime","Error", "by", "serializing", "Beautiful","Soup", "Treason", "Adultery", "Jewish", "excursion"]:
		print("Searching for: ",word)
		ion.translate("moot")
	ui = GUI(ion.history)
	


